package cn.interestingshop.dao.impl;


import cn.interestingshop.dao.BaseDao;
import cn.interestingshop.dao.UserAddressDao;
import cn.interestingshop.entity.UserAddress;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class UserAddressDaoImpl extends BaseDao implements UserAddressDao {

    @Override
    public List<UserAddress> selectAll(Integer userId) {
        List<UserAddress> list = new ArrayList<>();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            //1. 加载驱动
            //2. 获取连接对象
            conn = getConnection();
            //3. 定义sql语句
            String sql="select * from t_user_address where user_id = ? ";
            //4. 创建执行对象
            ps = conn.prepareStatement(sql);
            //5. 填充参数
            ps.setInt(1, userId);
            //6. 执行sql语句
            rs = ps.executeQuery();
            //7. 分析返回结果
            while (rs.next()) {
                UserAddress userAddress = new UserAddress();
                userAddress.setId(rs.getInt("id"));
                userAddress.setUserId(rs.getInt("user_id"));
                userAddress.setAddress(rs.getString("address"));
                userAddress.setCreateTime(rs.getString("create_time"));
                userAddress.setRemark(rs.getString("remark"));
                userAddress.setIsDefault(rs.getInt("is_default"));
                list.add(userAddress);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //8.释放资源关闭连接
            closeAll(rs, ps, conn);
        }
        return list;
    }

    @Override
    public int insert(UserAddress userAddress) {
        String sql="INSERT INTO `t_user_address`(`user_id`, `address`, `create_time`, `remark`) " +
                "VALUES (?, ?, ?, ?)";
        return executeUpdate(sql,new Object[]{
                userAddress.getUserId(),
                userAddress.getAddress(),
                userAddress.getCreateTime(),
                userAddress.getRemark()
        });
    }

}
